using System;
using System.Collections.Generic;

namespace Clandestine.Input.OSX
{
	internal static class OSXDeviceLoader
	{
		// not tested for more than one joystick.
		public static List<JoystickDevice> LoadJoysticks()
		{
			List<JoystickDevice> devices = new List<JoystickDevice>();
			
			// Build a device list of all joysticks.
			HIDUtilities.HIDBuildDeviceList((uint)HIDUtilities.UsagePages.kHIDPage_GenericDesktop, (uint)HIDUtilities.GenericDesktop.kHIDUsage_GD_Joystick);
			if (!HIDUtilities.HIDHaveDeviceList())
				return devices; // empty
			
			// Iterate through, creating devices.
			uint deviceCount = HIDUtilities.HIDCountDevices();
			IntPtr device = HIDUtilities.HIDGetFirstDevice();
			for (int i= 0; i < deviceCount; i++)
			{
				// Check it's a joystick -- I don't think this will EVER EVER throw the exception, unless OSX is *fucked*
				if ((HIDUtilities.IOHIDDevice_GetPrimaryUsagePage(device) != (uint)HIDUtilities.UsagePages.kHIDPage_GenericDesktop) 
				|| (HIDUtilities.IOHIDDevice_GetPrimaryUsage(device) != (uint)HIDUtilities.GenericDesktop.kHIDUsage_GD_Joystick))
					throw new Exception();
					
				// Create device.
				devices.Add(new OSXJoystickDevice(device));
				
				// Get next device
				device = HIDUtilities.HIDGetNextDevice(device);
			}
			
			return devices;
		}
	}
}

